<template>
  <div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="80px"
      class="demo-ruleForm"
    >
      <el-form-item label="账号" prop="userId">
        <el-input
          v-model.number="ruleForm.userId"
          class="userId"
          placeholder="输入账号"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="ruleForm.password"
          class="password"
          placeholder="输入密码"
          type="password"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    var validateId = (rule, value, callback) => {
      let reg = /^\d{12}$/g;
      if (value === "") {
        callback(new Error("请输入账号"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入12位数字"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        userId: "",
        password: "",
      },
      rules: {
        userId: [{ required: true, validator: validateId, trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 18,
            message: "长度在 6 到 18 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    open() {
      //弹窗
      this.$alert("账号或密码不完整，请检查后在输入！", "", {
        confirmButtonText: "确定",
      });
    },
    async submit() {
      try {
        console.log("ruleForm", this.ruleForm);
        await this.$store.dispatch("user/userLogin", this.ruleForm);
        this.$router.push({ path: "/" });
      } catch (error) {
        console.log("失败");
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submit();
        } else {
          this.open();
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>

</style>